package edu.xmut.kakamusic.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;

import edu.xmut.kakamusic.MainActivity;
import edu.xmut.kakamusic.R;
import edu.xmut.kakamusic.utils.SPUtils;

public class SplashActivity extends AppCompatActivity {

    private ImageView ivSplashImage;
    private Button btnSplashSkip;

    private Boolean isSkip = Boolean.FALSE;
    private Boolean isBack = Boolean.FALSE;
    private boolean hasLogin;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        initView();
        detectionHasLoggedIn();
        doGoToHome();
    }

    private void detectionHasLoggedIn() {
        SPUtils spUtils = new SPUtils(this);
        hasLogin = spUtils.getBoolean("hasLogin", false);
    }

    private void doGoToHome() {
        new Handler().postDelayed(() -> {
            if (!isSkip && !isBack) {
                Intent intent;
                if (hasLogin) {
                    intent = new Intent(SplashActivity.this, MainActivity.class);
                } else {
                    intent = new Intent(SplashActivity.this, LoginActivity.class);
                }
                startActivity(intent);
                finish();
            }
        }, 2000);
    }

    private void initView() {
        ivSplashImage = findViewById(R.id.iv_splash_image);
        btnSplashSkip = findViewById(R.id.btn_splash_skip);

        Glide.with(this)
                .load("https://art.pixilart.com/7badccc6206bf0f.gif")
                .into(ivSplashImage);
        btnSplashSkip.setOnClickListener(this::skip);
    }

    private void skip(View view) {
        isSkip = true;
        Intent intent;
        if (hasLogin) {
            intent = new Intent(SplashActivity.this, MainActivity.class);
        } else {
            intent = new Intent(SplashActivity.this, LoginActivity.class);
        }
        startActivity(intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        isBack = true;
    }


}
